package com.tianji.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * Description: 发送http请求的
 *
 * @author chenjia
 * @version 1.0
 * @date 2024/12/25 9:46
 */
@Slf4j
public class ApiUtils {

    /**@Description: get请求
     * @param
     * @return
     * @version v1.0
     * @author jia
     * @date 2024/12/25 9:49
     */
    public static DyIcpRecordStatusResp queryRecordStatus(String authorizerAccessToken) throws Exception {
        String url = "https://open.douyin.com/api/apps/v1/icp_record/query_record_status/";
        HttpRequest request = HttpUtil.createGet(url);
        request.header("content-type","application/json");
        request.header("access-token", authorizerAccessToken);
        try (HttpResponse response = request.execute()) {
            log.info("queryRecordStatus: {}", response.body());
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return mapper.readValue(response.body(), DyIcpRecordStatusResp.class);
        }
    }

    /**@Description: post请求
     * @param
     * @return
     * @version v1.0
     * @author jia
     * @date 2024/12/25 9:50
     */
    public static MiniAppApiResult code2Session(String appid, String secret, String code) {
        String url = MINI_API_URL + "/v2/jscode2session";
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOpt("appid", appid);
        jsonObject.putOpt("secret", secret);
        jsonObject.putOpt("code", code);
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(jsonObject));
        log.info("code2Session: {}",result);
        return JSONUtil.toBean(result,MiniAppApiResult.class);
    }

    /**@Description: 获取响应二维码
     * @param
     * @return
     * @version v1.0
     * @author jia
     * @date 2024/12/25 9:51
     */
    public static void getQrcode(String authorizer_access_token, String version, String path) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOpt("version", version);
        if(!StrUtil.isBlank(path)){
            jsonObject.putOpt("path", path);
        }
        URL url = new URL(SERVER_API_URL + "/v1/microapp/app/qrcode?component_appid=" + APP_ID + "&authorizer_access_token=" + authorizer_access_token);
        // 打开连接并获取HttpURLConnection对象
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        connection.getOutputStream().write(JSONUtil.toJsonStr(jsonObject).getBytes(StandardCharsets.UTF_8));
        // 发送请求并获取响应码
        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);
        // 读取响应内容
        InputStream in = connection.getInputStream();
        BufferedImage bufferedImage = ImageIO.read(in);
        File outputFile = new File("/Users/zhangjun/Downloads/dyminiapp-qr.png");
        // 保存图片文件
        ImageIO.write(bufferedImage, "png", outputFile);
        // 关闭流
        in.close();
        // 关闭连接
        connection.disconnect();
    }
}
